//
//  KARepaymentDetails.swift
//  kano
//
//  Created by Frank on 2024/9/19.
//

import UIKit

class KARepaymentDetails: KABaseVC {
    
    static let var_itemCellId = "KABillDetailPeriodCell"
    lazy var var_tableView: UITableView = {
        let var_tableView = UITableView(frame: CGRect(x: kscale(12), y: UIDevice.ka_fullNavHeight, width: view.width-kscale(24), height: UIDevice.ka_viewHeight), style: .grouped)
        var_tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
//        var_tableView.register(KARepayDetailSectionHeader.self, forHeaderFooterViewReuseIdentifier: "KARepayDetailSectionHeader")
        var_tableView.dataSource = self
        var_tableView.delegate = self
        var_tableView.separatorStyle = .none
        var_tableView.separatorColor = UIColor.clear
        var_tableView.bounces = true
        var_tableView.tableHeaderView = tableHeader
        var_tableView.tableFooterView = var_tableFooter
        return var_tableView
    }()
    
    lazy var tableHeader = {
        var tableHeader = KARepaymentDetailHeader(frame: CGRectMake(0, 0, view.width-kscale(24), 157))
        tableHeader.handler = { [self] in
            selectLoanIndex = 0
            let sectionModel = var_dataArray.first
            let allSelected = unPaySubLoans.allSatisfy { $0.select }
            sectionModel?.select = allSelected ? true : false
            var_tableView.reloadData()
        }
        return tableHeader
    }()

    lazy var var_tableFooter: KAApplyFooter = {
        let var_tableFooter = KAApplyFooter()
        var_tableFooter.backgroundColor = .colorf2f2f5
        var_tableFooter.var_loginButton.setTitle("I have made this bank transfer", for: .normal)
        var_tableFooter.var_loginButton.addTarget(self, action: #selector(ka_loanBtnClick), for: .touchUpInside)
        return var_tableFooter
    }()
    
    @objc func ka_loanBtnClick() {
//        navigationController?.popViewController(animated: true)
        for vc in navigationController!.viewControllers {
            if vc.isKind(of: KABillListVC.self) {
                let billVC = vc as! KABillListVC
                navigationController?.popToViewController(billVC, animated: true)
                return
            }
        }
        navigationController?.popViewController(animated: true)
    }
    
    var detailId: String = ""

    init(with id: String) {
        super.init(nibName: nil, bundle: nil)
        detailId = id
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .colorf2f2f5
        
        view.addSubview(var_tableView)
        ka_showCustomerNavBar(type: .normal)
        var_navBar.var_titleLabel.text = "Obtain credit limit"
        
        requestData()
    }
    
    var model: KABillDetailModel?
    var vaModel: KAVAModel?

    func requestData() {
        view.showLoading()
        let dispatchGroup = DispatchGroup()

        dispatchGroup.enter()
        let paraDic:[String : Any] = [ "userGid":KAUserManager.shared.user.userGid, "loanGid": detailId ]
        billProvider.request(.billDetail(paraDic)) { [self] result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KABillDetailModel>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.content else { return }
                            model = content
                            unPaySubLoans =  model!.subLoans?.filter {$0.repaymentStatus != 3} ?? []
                            unPaySubLoans.first?.select = true
                            tableHeader.model = model
                        }
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
            dispatchGroup.leave()
        }

        dispatchGroup.enter()
        let paramDic:[String : Any] = [ "userGid":KAUserManager.shared.user.userGid]
        billProvider.request(.valist(paramDic)) { [self] result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<[KAVAModel]>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.content else { return }
                            if content.count > 0 {
                                vaModel = content.first
                            }
                        }
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
            dispatchGroup.leave()
        }
        
        dispatchGroup.notify(queue: .main) { [self] in
            view.hideLoading()
            configData()
        }
    }
    
    lazy var var_dataArray = [KASectionInfo]()
    
    var selectLoanIndex: Int = 0

    var unPaySubLoans: [KABillDetailSubLoans] = []

    func configData() {
        //展示分期数据
        if unPaySubLoans.count > 0 {
            let subLoanSec = KASectionInfo(showHeader: true, open: true, sectionTitle: "\("1")/\(unPaySubLoans.count) selected", type: .subLoan)
            var_dataArray.append(subLoanSec)
        }
        let bankAcc = KARowInfo(title: "Bank account", subTitle: model!.withdrawCardNo, isFirst: true, type: .bankAccount)
        let bankVA = KARowInfo(title: "Bank VA", subTitle: vaModel?.bankVA ?? "", isFirst: true, type: .bankVA,showSubSender: true)
        let bankName = KARowInfo(title: "Bank name", subTitle: vaModel?.bankShortName ?? "", isLast: true, type: .bankName)
        let receiverName = KARowInfo(title: "Receiver Name", subTitle: vaModel?.receiverShowName ?? "", isLast: true, type: .bankName)
        let loanInfoSec = KASectionInfo(showHeader: true, open: true, sectionList: [bankVA, bankName, receiverName], type: .bankInfo)
        var_dataArray.append(loanInfoSec)
        
        var_tableView.reloadData()
    }
}

extension KARepaymentDetails : UITableViewDataSource, UITableViewDelegate {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return var_dataArray.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let sectionModel = var_dataArray[section]
        switch sectionModel.type {
        case .subLoan:
            return sectionModel.open ? unPaySubLoans.count : 0
        case .bankInfo:
            return sectionModel.open ? sectionModel.sectionList.count : 0
        default:
            return 0
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let sectionModel = var_dataArray[indexPath.section]
        switch sectionModel.type {
        case .subLoan:
            let cellModel = unPaySubLoans[indexPath.row]
            let var_cell: KARepayDetailPeriodCell = KARepayDetailPeriodCell.ka_cell(for: tableView)
            var_cell.titleLabel.text = "\(cellModel.index)st phase"
            var_cell.amountLabel.text = "₦\(cellModel.leftAmount)"
            var_cell.contentLabel.text = Date.ka_stringWith(timestamp: cellModel.dueTime, format: "dd/MM/yyyy")
            var_cell.var_selectImg.image = cellModel.select ? UIImage(named: "repay_sel") : UIImage(named: "repay_unsel")
            if indexPath.row == 0 {
                var_cell.topCorner = true
                var_cell.bottomCorner = false
            } else if (indexPath.row == unPaySubLoans.count - 1) {
                var_cell.topCorner = false
                var_cell.bottomCorner = true
            } else if (indexPath.row == unPaySubLoans.count - 1 && indexPath.row == 0) {
                var_cell.topCorner = true
                var_cell.bottomCorner = true
            }
            return var_cell
        case .bankInfo:
            let cellModel = sectionModel.sectionList[indexPath.row]
            let var_cell: KARepayDetailBankCell = KARepayDetailBankCell.ka_cell(for: tableView)
            var_cell.var_titleLabel.text = cellModel.title
            var_cell.var_contentLabel.text = cellModel.subTitle
            var_cell.showSubSender = cellModel.showSubSender

//            var_cell.var_explainBtn.isHidden = cellModel.showTitleTip ? false : true
            var_cell.cellModel = cellModel
            return var_cell
        default:
            return UITableViewCell()
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let sectionModel = var_dataArray[indexPath.section]
        switch sectionModel.type {
        case .subLoan:
            return kscale(28)
        case .bankInfo:
            return kscale(33)
        default:
            return .leastNonzeroMagnitude
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let sectionModel = var_dataArray[indexPath.section]
        if sectionModel.type == .subLoan {
            let cellModel = unPaySubLoans[indexPath.row]

            //设置必须顺序选中分期
            if indexPath.row > selectLoanIndex + 1 || indexPath.row < selectLoanIndex {
                view.makeToast("Please select in order")
                return
            } else {
                selectLoanIndex = cellModel.select ? indexPath.row - 1 : indexPath.row
            }
            //修改选中cell模型数据
            cellModel.select = !cellModel.select
            //判断是否全部选中，全选中修改sectionModel状态
            let allSelected = unPaySubLoans.allSatisfy { $0.select }
            sectionModel.select = allSelected ? true : false
            
            tableHeader.model = model
            
            var_tableView.reloadData()
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let sectionModel = var_dataArray[section]
        switch sectionModel.type {
        case .subLoan:
            let header = KARepayDetailSectionHeader(frame: CGRectMake(0, 0, tableView.width, kscale(44)))
            let count = unPaySubLoans.filter { $0.select }.count
            header.titleLabel.text = "\(count)/\(unPaySubLoans.count) selected"
            header.selectBtn.isSelected = sectionModel.select
            header.var_handler = {
                sectionModel.open = !sectionModel.open
                tableView.reloadData()
            }
            header.var_selectHandler = { [self] select in
                if select {
                    selectLoanIndex = unPaySubLoans.count - 1
                } else {
                    selectLoanIndex =  -1
                }
                unPaySubLoans.forEach { $0.select = select }
                sectionModel.select = select
                tableHeader.model = model
                tableView.reloadData()
            }
            return header
        case .bankInfo:
            let header = KARepayMethodSectionHeader(frame: CGRectMake(0, 0, tableView.width, kscale(44)))
            return header
        default:
            return UIView()
        }
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        let sectionModel = var_dataArray[section]
        switch sectionModel.type {
        case .subLoan:
            return kscale(44)
        case .bankInfo:
            return kscale(68)
        default:
            return .leastNonzeroMagnitude
        }
    }

    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footer = KARepayDetailSectionFooter(frame: CGRectMake(0, 0, tableView.width, kscale(24)))
        return footer
    }
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return kscale(30)
    }
}

